package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    /**
     * 新增菜品
     * @param dishDTO
     */
    @Override
    public void addDish(DishDTO dishDTO) {
        //1.封装添加菜品参数
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateUser(BaseContext.getCurrentId());
        //2.向菜品表插入1条数据
        dishMapper.addDish(dish);
        //3、校验口味信息是否为空
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors == null || flavors.size() == 0) {
            return;
        }
        //4、获取insert语句生成的主键值
        Long dishId = dish.getId();
        //5、封装菜品口味参数
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishId);
        }
        //6、向口味表插入n条数据
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 分页查询菜品信息
     * @param pageQueryDTO
     * @return
     */
    @Override
    public PageResult pageDish(DishPageQueryDTO pageQueryDTO) {
        //分页插件
        PageHelper.startPage(pageQueryDTO.getPage(),pageQueryDTO.getPageSize());
        Page<DishVO> pageinfo = dishMapper.pageDish(pageQueryDTO);
        return new PageResult(pageinfo.getTotal(),pageinfo.getResult());
    }

    /**
     * 批量删除菜品信息
     * @param ids
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //先判断选择的菜品中是否有起售的菜品
         int countStatus = dishMapper.queryStatusById(ids);
         if (countStatus>0){
             throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
         }
        //判断选择的菜品是否有被套餐关联
        int countSetMeal = setmealDishMapper.countByDishId(ids);
         if (countSetMeal>0){
             throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
         }
        //批量删除菜品信息
        dishMapper.deleteBatch(ids);
        //批量删除口味信息
        dishFlavorMapper.deleteBatchByDishId(ids);
    }

    /**
     * 根据id查询菜品信息
     * @param id
     * @return
     */
    @Override
    public DishVO getById(Long id) {
        //根据id查询菜品数据
        Dish dish = dishMapper.getById(id);
        //根据菜品id查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorMapper.getByDishId(id);
        //将查询到的数据封装到VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    /**
     *修改菜品信息
     * @param dishDTO
     */
    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        //第一步: 修改菜品基本信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
//        dish.setUpdateTime(LocalDateTime.now());
//        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.update(dish);
        //第二步: 删除原有的口味数据
        Long dishId = dish.getId();
        ArrayList<Long> list = new ArrayList<>();
        list.add(dishId);
        dishFlavorMapper.deleteBatchByDishId(list);
        //第三步: 重新添加口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors==null || flavors.size()==0){
            return;
        }
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dish.getId());
        }
        dishFlavorMapper.insertBatch(flavors);
    }

    /**
     * 菜品起售停售
     * @param status
     * @param id
     */
    @Override
    @Transactional
    public void startOrStop(Integer status, Long id) {
        Dish dishUpdate = Dish.builder().id(id).status(status).build();
        dishMapper.update(dishUpdate);
        if (status== StatusConstant.DISABLE){
            // 如果是停售操作，还需要将包含当前菜品的套餐也停售
            List<Long> dishIds = new ArrayList<>();
            // select setmeal_id from setmeal_dish where dish_id in (?,?,?)
            dishIds.add(id);
            List<Long> setMealIds = setmealDishMapper.startOrStop(dishIds);
            if (setMealIds!=null && setMealIds.size()>0){
                for (Long setMealId : setMealIds) {
                    Setmeal setmealUpdate = Setmeal.builder().id(setMealId).status(status).build();
                    setmealMapper.update(setmealUpdate);
//                    setmealUpdate.setUpdateUser(BaseContext.getCurrentId());
//                    setmealUpdate.setUpdateTime(LocalDateTime.now());
                }
            }

        }
    }
    /**
     * 根据分类id查询菜品
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId) {
        Dish dish = Dish.builder().categoryId(categoryId).status(StatusConstant.ENABLE).build();
        return dishMapper.getByCategoryId(dish);
    }
    /**
     * select a.*,b.name from dish a left join dish_flavor b on b.dish_id = a.id
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


}
